<!-- 节能分析 -->
<template>
  <div class="saving-container">
    <div v-if="!showAnalysis" v-loading="loading">
      <div class="flex-center">
        <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
          <px-form-item label="节能事项名称" prop="name" style="width: 260px">
            <px-input v-model="queryParams.name" placeholder="请输入节能事项名称" clearable />
          </px-form-item>
          <px-form-item label="执行时间" prop="time" style="width: 280px">
            <px-date-picker
              v-model="queryParams.time"
              type="monthrange"
              value-format="YYYY-MM"
              range-separator="-"
              start-placeholder="开始月份"
              end-placeholder="结束月份"
            />
          </px-form-item>
          <div class="search-form-btn">
            <px-button type="primary" @click="handleQuery">查询</px-button>
            <px-button @click="resetQuery">重置</px-button>
          </div>
        </px-form>
      </div>
      <div class="table-top">
        <px-button v-has="'ALL_ENERGY_SAVINGANALYSIS_ADD'" type="primary" @click="handleAdd">+节能决策</px-button>
      </div>
      <div v-loading="loading" class="table-content">
        <px-table height="calc(100vh - 340px)" :data="tableData" size="small" border class="common-table">
          <px-table-column type="index" label="序号" fixed width="55" align="center" />
          <px-table-column prop="name" label="节能事项名称" min-width="120" show-overflow-tooltip />
          <px-table-column prop="kind" label="能源类型" min-width="120" show-overflow-tooltip>
            <template #default="scope">
              {{ energyData[scope.row.kind] }}
            </template>
          </px-table-column>
          <px-table-column prop="" label="执行时间" min-width="150" show-overflow-tooltip>
            <template #default="scope"> {{ scope.row.startTime }} - {{ scope.row.endTime }} </template>
          </px-table-column>
          <px-table-column prop="executor" label="执行人" min-width="120" show-overflow-tooltip />
          <px-table-column prop="owner" label="负责人" min-width="120" show-overflow-tooltip />
          <px-table-column prop="description" label="节能描述" min-width="120" show-overflow-tooltip />
          <px-table-column prop="createByName" label="创建人" min-width="120" show-overflow-tooltip />
          <px-table-column prop="createTime" label="创建时间" min-width="120" show-overflow-tooltip />
          <px-table-column label="操作" width="150" fixed="right" align="center">
            <template #default="scope">
              <px-tooltip content="编辑" placement="top">
                <px-button v-has="'ALL_ENERGY_SAVINGANALYSIS_EDIT'" link icon="Edit" type="primary" @click="handleEdit(scope.row)" />
              </px-tooltip>
              <px-tooltip content="分析报表" placement="top">
                <px-button v-has="'ALL_ENERGY_SAVINGANALYSIS_ANALYSIS'" link icon="DataAnalysis" type="primary" @click="handleAnalysis(scope.row)" />
              </px-tooltip>
              <px-tooltip content="删除" placement="top">
                <px-button v-has="'ALL_ENERGY_SAVINGANALYSIS_DELETE'" link icon="Delete" type="danger" @click="handleDelete(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="pageNum"
          v-model:limit="pageSize"
          class="table-pagination"
          :total="total"
          @pagination="handleQuery"
        />
      </div>

      <div v-if="editVisible">
        <EditForm v-model:visible="editVisible" :handleType="handleType" :rowData="rowData" @save="saveEdit" />
      </div>
    </div>
    <div v-else>
      <Analysis :rowData="rowData" :energyMap="energyData" @goBack="goBack" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from "vue";
import EditForm from "@/views/common/energy/savingAnalysis/component/editForm.vue";
import Analysis from "@/views/common/energy/savingAnalysis/component/analysis.vue";
import { getListAPI, saveListAPI, deleteListAPI } from "@/api/energy/savingAnalysis";
import { PxMessage, PxMessageBox } from "px-ui";
import dayjs from "dayjs";

defineOptions({
  name: "ALL_ENERGY_SAVINGANALYSIS"
});

const formRef = ref(null);

const state = reactive({
  queryParams: {
    name: "",
    time: []
  },
  loading: false,
  total: 10,
  pageNum: 1,
  pageSize: 20,
  tableData: [{ name: "111" }],
  editVisible: false,
  handleType: "",
  rowData: {},
  showAnalysis: false
});
const { queryParams, loading, total, pageNum, pageSize, tableData, editVisible, handleType, rowData, showAnalysis } = toRefs(state);

const energyData = ref({
  electricity: "电",
  running: "自来水",
  reclaim: "再生水",
  ng: "天然气",
  steam: "蒸汽",
  hot: "热水",
  cda: "CDA",
  n2: "N2",
  h2: "H2",
  o2: "O2",
  ar: "Ar",
  he: "He",
  co2: "CO2",
  diesel: "柴油"
});

onMounted(() => {
  handleQuery();
});

// 查询
const handleQuery = async () => {
  console.log("aaaa", state.queryParams.time);
  try {
    state.loading = true;
    const params = {
      pageNum: state.pageNum,
      pageSize: state.pageSize,
      name: state.queryParams.name,
      startDate: state.queryParams.time && state.queryParams.time.length > 0 ? state.queryParams.time[0] + "-01" : "",
      endDate: state.queryParams.time && state.queryParams.time.length > 0 ? dayjs(state.queryParams.time[1]).endOf("month").format("YYYY-MM-DD") : ""
    };
    const res = await getListAPI(params);
    state.total = res.total;
    res.data?.forEach(i => {
      i.createTime = i.createTime.split(" ")[0];
      i.endTime = i.endTime.split(" ")[0];
      i.startTime = i.startTime.split(" ")[0];
    });
    state.tableData = res.data;
  } catch (error) {
    console.log(error);
  } finally {
    state.loading = false;
  }
};

// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  handleQuery();
};

// 新增
const handleAdd = () => {
  state.rowData = {};
  state.handleType = "Add";
  state.editVisible = true;
};

// 编辑
const handleEdit = row => {
  state.rowData = row;
  state.handleType = "Edit";
  state.editVisible = true;
};

// 删除
const handleDelete = row => {
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      await deleteListAPI({ id: row.id });
      PxMessage.success("删除成功");
      handleQuery();
    })
    .catch(() => {});
};

// 分析报表
const handleAnalysis = row => {
  state.rowData = row;
  state.showAnalysis = true;
};

const goBack = () => {
  state.showAnalysis = false;
};

const saveEdit = async data => {
  console.log("表单", data);
  const params = {
    id: state.handleType === "Edit" ? state.rowData.id : null,
    name: data.name,
    kind: data.energy,
    startTime: dayjs(data.executeTime[0]).format("YYYY-MM") + "-01" || "",
    endTime: dayjs(data.executeTime[1]).endOf("month").format("YYYY-MM-DD") || "",
    executor: data.executor,
    owner: data.leader,
    description: data.description
  };
  const res = await saveListAPI(params);
  PxMessage.success(state.handleType === "Add" ? "新增成功" : "编辑成功");
  state.editVisible = false;
  handleQuery();
};
</script>

<style lang="scss" scoped>
.saving-container {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: calc(100vh - 133px);
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
}

.flex-center {
  display: flex;
  align-items: center;
}

.search-form {
  display: flex;
  align-items: center;

  .search-form-btn {
    margin-bottom: 16px;
  }
}

.table-top {
  margin-bottom: 8px;
}
</style>
